<template>
  <div>
    <page-main>
      <el-steps :active="active" finish-status="success">
        <el-step title="挑选物品" description="" />
        <el-step title="填写信息" description="" />
        <el-step title="完成" description="" />
      </el-steps>
    </page-main>
    <page-main v-if="active === 0">
      <TableHeader :title="selectedMap.size === 0 ? '请选择你要借的体育用品' : '已选：'">
        <template #content>
          <span v-if="selectedMap.size === 0">当前未选择</span>
          <template v-for="(item, key) in selectedMap">
            <span v-if="selectedMap.size - 1 === key" :key="key">{{ `${item[1].name}（ID:${item[0]}）。` }}</span>
            <span v-else :key="key">{{ `${item[1].name}（ID:${item[0]}）、` }}</span>
          </template>
        </template>
      </TableHeader>
      <div class="multiple-table">
        <el-table
          ref="multipleTable"
          v-loading="isTableLoading"
          height="calc(100vh - 518px)"
          :data="dataList"
          border
          stripe
          highlight-current-row
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <template v-for="item of columns">
            <el-table-column :key="item.prop" :prop="item.prop" :label="item.label" :width="item.width" />
          </template>
        </el-table>
        <Page :current-page="currentPage" :total="total" :page-size="pageSize" @change-current-page="changeCurrentPage" @change-page-size="changePageSize" />
      </div>
    </page-main>

    <div v-if="active === 1" class="equip-box">
      <div class="equip-card blue">
        <h3 class="title overflow">借用时间（小时）</h3>
        <p class="desc overflow">请选择你要借用的时间</p>
        <div class="input">
          <el-input-number v-model="form.hours" size="small" :min="1" :max="3600" />
        </div>
      </div>
      <div v-for="(item, key) in selectedMap" :key="key" class="equip-card">
        <h3 class="title overflow">{{ item[1].name }}</h3>
        <p class="desc overflow">{{ `剩余：${item[1].rep}  总数：${item[1].sum}` }}</p>
        <div class="input">
          <el-input-number v-model="form.equipList[key].count" size="small" :min="1" :max="item[1].rep" />
        </div>
      </div>
    </div>
    <!-- <page-main v-if="active === 2">
      <el-button @click="ceshi">压力测试（数量改成1000）</el-button>
    </page-main> -->
    <page-main v-if="active === 2">
      <h2>确认信息:</h2>
      <h3>借用时间:{{ form.hours }}小时</h3>
      <p v-for="item in form.equipList" :key="item.id">
        <span>{{ `${selectedMap.get(item.equipId).name}(ID:${item.equipId})：借` }}</span>
        <span style="color: #f56c6c;">{{ item.count }}</span>
        <span>个；</span>
      </p>
    </page-main>

    <page-main v-if="active === 3">
      <result v-loading="onLoading" type="success" title="借出成功" desc="您的借单已通过，请前往仓库领取物品">
        <el-button type="primary" size="small" @click="navageteTo">查看我的借单</el-button>
        <el-button size="small" @click="reload(2)">再借一单</el-button>
      </result>
    </page-main>

    <fixed-action-bar>
      <el-button :disabled="active === 0 || active === maxActive" @click="goPrevious">返回上一步</el-button>
      <el-button :disabled="active === maxActive" type="primary" @click="goNext">
        <span v-if="active === 2">确认无误，提交</span>
        <span v-else>好了，下一步</span>
      </el-button>
    </fixed-action-bar>
  </div>
</template>

<script>
import { equip } from '@/api/equip'
import { borrow } from '@/api/borrow'
import page from '@/mixins/page'

export default {
  components: {},
  mixins: [page],
  inject: ['reload'],
  data() {
    return {
      columns: [
        {
          prop: 'id',
          label: 'id',
          width: '80px'
        },
        {
          prop: 'name',
          label: '用品名'
        },
        {
          prop: 'price',
          label: '价格'
        },
        {
          prop: 'class',
          label: '种类'
        },
        {
          prop: 'sum',
          label: '总数'
        },
        {
          prop: 'rep',
          label: '现有库存'
        }
      ],
      dataList: [],
      searchParams: {},
      form: {},
      active: 0,
      maxActive: 3,
      selectedEquipList: [],
      multipleSelection: [], // 多选记忆
      isTableLoading: false,
      selectedMap: new Map(),
      isManualOperation: 0, // 表格恢复时，手动调用toggleRowSelection，也会触发@selection-change。这里手动设置标记，当表格恢复时，不要初始化selectedMap
      onLoading: false
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    // 获取table数据
    async getList() {
      const params = {
        current: this.currentPage,
        size: this.pageSize,
        param: this.searchParams
      }
      this.isTableLoading = true
      const result = await equip.list(params)
      this.dataList = result.data.equips
      this.total = result.data.total * 1
      this.isTableLoading = false
      this.$nextTick(() => {
        this.pageSelectionInit(this.dataList)
      })
    },
    async submit() {
      this.onLoading = true
      await borrow.put({ ...this.form, userId: JSON.parse(this.$store.state.user.account).id }).catch((e) => {
        console.error(e)
        this.$message.error('发生错误，请重新选择')
        this.reload(2)
        this.onLoading = false
      })
      this.onLoading = false
    },
    goNext() {
      if (this.active === 0 && this.selectedMap.size === 0) {
        this.$message.warning('请选择你要借的东西')
        return
      }
      if (this.active < this.maxActive) {
        this.active++
      }
      if (this.active === 0) {
        this.getList()
      }
      if (this.active === 1) {
        this.form = {
          hours: 0,
          equipList: []
        }
        this.selectedMap.forEach((item) => {
          this.form.equipList.push({
            equipId: item.id,
            count: 1
          })
        })
      }
      if (this.active === 3) {
        this.submit()
      }
    },
    goPrevious() {
      // 返回第一步前，删掉选择的物品数据
      if (this.active === 1) {
        this.selectedEquipList = []
      }
      if (this.active > 0) {
        this.active--
      }
      if (this.active === 0) {
        this.getList()
      }
    },

    changePageSize(pageSize) {
      this.pageSize = pageSize
      this.currentPage = 1
      this.isManualOperation = true
      this.getList()
    },
    changeCurrentPage(currentPage, pageSize) {
      this.currentPage = currentPage
      this.pageSize = pageSize
      this.isManualOperation = true
      this.getList()
    },
    // 表格：储存当前页面的选中情况
    handleSelectionChange(val) {
      this.selectedEquipList = val
      this.pageSelectionSave(this.dataList, this.selectedEquipList)
    },
    // 表格：切换页面之前保存页面
    pageSelectionSave(pageArr = [], selectedArr = []) {
      // console.log('来碰一碰？', this.isManualOperation)
      if (this.isManualOperation) {
        this.isManualOperation = false
        return
      }
      // console.log('哇哦，击穿了')
      let tempMap = new Map(this.selectedMap)
      pageArr.forEach((item) => {
        if (tempMap.has(item.id)) {
          tempMap.delete(item.id)
        }
      })
      selectedArr.forEach((item) => {
        tempMap.set(item.id, item)
      })
      this.selectedMap = tempMap // 必须这样写，不然dom无法刷新。使用this.$forceUpdate()后，v-for仍然异常
    },
    // 表格：切换页面之后，恢复该页面选中状态
    pageSelectionInit(pageArr = []) {
      let tempArr = []
      pageArr.forEach((item) => {
        if (this.selectedMap.has(item.id)) {
          tempArr.push(item)
        }
      })
      console.log('从map中恢复已选中：', JSON.stringify(tempArr))
      this.toggleSelection(tempArr)
    },
    // 表格：选中多个行,切换页面选中状态
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.isManualOperation = true
          let rowIndex = 0
          this.dataList.forEach((item, index) => {
            if (item.id === row.id) {
              rowIndex = index
            }
          })
          this.$refs.multipleTable.toggleRowSelection(this.dataList[rowIndex], true)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    ceshi() {
      this.form.equipList[0].count = 1000
    },
    navageteTo() {
      this.$router.push({ name: 'borrow-list' })
    }
  }
}
</script>
<style lang="scss" scoped>
.multiple-table {
    ::v-deep .el-table {
        min-height: 100px;
    }
}
.equip-box {
    margin: 0 20px 20px 20px;
    display: flex;
    flex-wrap: wrap;
    .blue {
        &:hover {
            background: linear-gradient(270deg, #acccff 0%, #6692ff 100%);
            .title {
                color: #fff;
            }
            .desc {
                color: #fff;
            }
            .input {
                ::v-deep .el-input-number--small {
                    flex: 1;
                }
            }
        }
    }
    .equip-card {
        padding: 10px;
        margin: 0 20px 20px 0;
        background-color: #fff;
        width: 210px;
        height: 130px;
        transition: all 0.2s linear;
        &:hover {
            box-shadow: 0 15px 30px rgb(0 0 0 / 10%);
            -webkit-transform: translate3d(0, -2px, 0);
            transform: translate3d(0, -2px, 0);
        }
        .title {
            margin: 0 0 2px;
            text-align: center;
            font-size: 16px;
            font-weight: 400;
            color: #333;
        }
        .desc {
            margin: 0 0 10px;
            text-align: center;
            height: 18px;
            font-size: 12px;
            color: #b0b0b0;
        }
        .overflow {
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
        }
        .input {
            display: flex;
            margin: 20px 20px 0;
            ::v-deep .el-input-number--small {
                flex: 1;
            }
        }
    }
}
</style>
